import wx
import os
import threading
import asyncio
import re
import time


Bind = {
    "pushButton":"clicked",
    "comboBox":"currentIndexChanged",
    "radioButton":"clicked",
    "checkBox":"stateChanged",
    "lineEdit":"textChanged",
}



class maingui(wx.Frame):
    def __init__(self,per):
        wx.Frame.__init__(self,per,title="界面转换",size=wx.Size(500,300))
        boxv = wx.BoxSizer(wx.VERTICAL)
        self.butonn = wx.Button(self)
        self.butonn.SetLabel("转换")
        self.text   = wx.TextCtrl(self)
        boxv.Add(self.text, 0, wx.EXPAND, 5)
        boxv.Add(self.butonn, 1, wx.EXPAND, 5)
        self.SetSizer(boxv)
        self.Layout()
        self.Centre(wx.BOTH)
        self.text.SetDropTarget(FileDrop(self.text))
        self.butonn.Bind(wx.EVT_BUTTON, self.on_click)
        self.mythr = mythread(self)
        self.mythr.start()

    def on_click(self,eve):
        paths = self.text.GetValue().split(";")
        mpath = os.path.dirname(os.path.dirname(paths[0]))
        self.butonn.Enable(False)
        addr = []
        for k,v in enumerate(paths):
            if v:
                self.mythr._coro(mydef,mpath,v,k)
                addr.append(k)
        self.mythr._coro(m_write,addr,mpath)



class FileDrop(wx.FileDropTarget):
    def __init__(self,windows):
        wx.FileDropTarget.__init__(self)
        self.windows = windows

    def OnDropFiles(self, x, y, filePath):
        if filePath:
            s = ""
            for i in filePath:
                s += i + ";"
            self.windows.SetValue(s)
            return True
        else:
            return False



class mythread(threading.Thread):
    def __init__(self,windows):
        threading.Thread.__init__(self)
        self.windows = windows
        self.daemon  = True
        self.loop    = asyncio.new_event_loop()
        self.mqueue  = asyncio.Queue(loop=self.loop)

    def run(self):
        self.loop.run_forever()

    def _coro(self,thr_call,*agr):
        asyncio.run_coroutine_threadsafe(thr_call(self.windows,self.mqueue,*agr), self.loop)



async def m_write(windows,queue,addr,mpath):
    mainfile = os.path.join(mpath,"main.py")
    #if os.path.exists(mainfile):
    #    os.remove(mainfile)

    p = open(mainfile, "a", encoding='utf-8')
    t1 = "\nimport sys\nfrom PyQt5.QtWidgets import QWidget,QApplication\n\n"
    name = None
    t2 = "\n\n\n"
    while addr:
        dic = await queue.get()
        t2 += "class {}_Gui(QWidget, {}.{}):\n".format(dic["name"].title(),dic["name"],dic["class"])
        t2 += "    def __init__(self):\n"
        t2 += "        super({}_Gui, self).__init__()\n".format(dic["name"].title())
        t2 += "        self.setupUi(self)\n"
        if dic["data"]:
            for key in dic["data"]:
                for k,v in enumerate(dic["data"][key]):
                    t2 += "        self.{}.{}.connect(lambda : self.on_{}({}))\n".format(v,Bind[key],key,k)
                    
        t2 += "        self.setWindowTitle('{}')\n\n".format(dic["name"])
        if dic["data"]:
            for key in dic["data"]:
                t2 += "    def on_{}(self,mint):\n        print('{}',mint)\n\n".format(key,key)
        t2 += "\n\n\n"
        t1 += "import {}\n".format(dic["name"])
        if not name:
            name = dic["name"].title() + "_Gui"
        addr.remove(dic["id"])
    t3 = "\nif __name__ == '__main__':\n    app = QApplication(sys.argv)\n    win = {}()\n    win.show()\n    sys.exit(app.exec_())\n\n\n".format(name)
    print(t1)
    print(t2)
    print(t3)
    p.write(t1)
    p.write(t2)
    p.write(t3)
    p.close()
    windows.butonn.Enable(True)



async def mydef(windows,queue,path,filepath,id):
    name   = os.path.basename(filepath).replace(".","")
    pypath = os.path.join(path,name)
    cmd = "pyuic5 -o {}.py {}".format(pypath,filepath)
    while 1:
        os.popen(cmd)
        await asyncio.sleep(0.5)
        if os.path.exists(pypath + ".py"):
            break
    with open(pypath + ".py",'r',encoding='utf-8') as f:
        filedata = f.read()
    res         = re.search("class (.*?)\(",filedata)
    dic = {}
    pushButton  = re.findall("self.(.*?) = QtWidgets.QPushButton\(Form\)",filedata)
    if pushButton:
        dic.update({pushButton[0].split("_")[0]:pushButton})
    comboBox    = re.findall("self.(.*?) = QtWidgets.QComboBox\(Form\)",filedata)
    if comboBox:
        dic.update({comboBox[0].split("_")[0]:comboBox})
    radioButton = re.findall("self.(.*?) = QtWidgets.QRadioButton\(Form\)",filedata)
    if radioButton:
        dic.update({radioButton[0].split("_")[0]:radioButton})
    checkBox    = re.findall("self.(.*?) = QtWidgets.QCheckBox\(Form\)",filedata)
    if checkBox:
        dic.update({checkBox[0].split("_")[0]:checkBox})
    lineEdit    = re.findall("self.(.*?) = QtWidgets.QLineEdit\(Form\)",filedata)
    if lineEdit:
        dic.update({lineEdit[0].split("_")[0]:lineEdit})
    mclass = res.group(1)
    await queue.put({"id":id,"class":mclass,"name":name,"data":dic})


if __name__ == '__main__':
    app = wx.App()
    maingui(None).Show(True)
    app.MainLoop()